<?php


namespace app\backstage\controller;


use app\backstage\logic\Account;
use app\backstage\model\KlOrder;
use think\Controller;
use think\Db;
use think\facade\Validate;

class Deduct extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => []],
    ];

    public function index()
    {
        $todayMoney = Db::table("pay_order_kl_backups")->where("status", 2)->where("create_date", date("Y-m-d"))->sum('total_fee') ?? 0;
        $yesterdayMoney = Db::table("pay_order_kl_backups")->where("status", 2)->where("create_date", date("Y-m-d", strtotime('-1 day')))->sum('total_fee') ?? 0;
        $thisMonthMoney = Db::table("pay_order_kl_backups")->where("status", 2)->where("create_date", ">=", date('Y-m-01'))->sum('total_fee') ?? 0;
        $lastMonthMoney = Db::table("pay_order_kl_backups")->where("status", 2)->where("create_date", ">=", date('Y-m-01', strtotime('first day of last month')))->where("create_date", "<=", date('Y-m-t', strtotime('last month')))->sum('total_fee') ?? 0;
        $allMoney = Db::table("pay_order_kl_config")->sum('money') ?? 0;

        $this->assign('todayMoney', getQuotient($todayMoney, 100));
        $this->assign('yesterdayMoney', getQuotient($yesterdayMoney, 100));
        $this->assign('thisMonthMoney', getQuotient($thisMonthMoney, 100));
        $this->assign('lastMonthMoney', getQuotient($lastMonthMoney, 100));
        $this->assign('allMoney', getQuotient($allMoney, 100));
        return $this->fetch();
    }

    /**
     * 添加扣量规则
     * @return mixed
     */
    public function addRule()
    {
        if (request()->isPost()) {
            $params = request()->param();
            $result = $this->validate($params, 'app\backstage\validate\DeductValidate.addRule');
            if (true !== $result) {
                $this->error($result);
            }
            $channel = \app\backstage\model\ManagerUser::get($params['channel_id']);
            $data['channel_id'] = $params['channel_id'];
            $data['agent_id'] = $channel->parent_id;
            $data['user_group'] = $params['user_group'];
            $data['register_day'] = $params['register_day'];
            $data['login_hour'] = $params['login_hour'];
            $data['odds'] = $params['odds'];
            $data['register_judg'] = 0;
            $data['login_judg'] = 0;
            if (isset($params['register_judg']) && $params['register_judg'] == 'on') {
                $data['register_judg'] = 1;
            }
            if (isset($params['login_judg']) && $params['login_judg'] == 'on') {
                $data['login_judg'] = 1;
            }
            $id = Db::table("pay_order_kl_config")->where("channel_id", $params['channel_id'])->value('id');
            if ($id) {
                $this->error('改投放号扣量规则已存在');
            }
            Db::table("pay_order_kl_config")->insert($data);
            $this->success();
        }
        $account = new Account();
        $channels = $account->getChannels(0);
        $this->assign('channels', $channels);
        return $this->fetch();
    }


    /**
     * 修改字段
     */
    public function changeField()
    {
        $params = request()->param();
        $result = $this->validate($params, 'app\backstage\validate\DeductValidate.changeField');
        if (true !== $result) {
            $this->error($result);
        }
        $field = input('field');
        $id = input('id');
        $value = input('value');
        if ($field == 'odds'){
            $rule = [
                'value' => 'require|float|gt:0|elt:1',
            ];
        }elseif ($field == 'register_day' || $field == 'login_hour'){
            $rule = [
                'value' => 'require|number|egt:0',
            ];
        }else{
            $rule = [
                'value' => 'require|in:0,1,2',
            ];
        }
        $validate   = Validate::make($rule);
        $result = $validate->check($params);
        if(!$result) {
            return errJson($validate->getError());
        }
        Db::table("pay_order_kl_config")->where("id", $id)->setField($field, $value);
        $this->success();
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function configList()
    {
        $agent_id = input('agent_id');
        $channel_id = input('channel_id');
        $start_date = input('start_date');
        $end_date = input('end_date');
        $page = input('page', 1);
        $limit = input('limit', 10);
        $order = input('order', 'id desc');
        $where = [];
        if ($channel_id != '') {
            $where[] = ['channel_id', '=', $channel_id];
        }
        if ($agent_id != '') {
            $where[] = ['agent_id', '=', $agent_id];
        }
        $list = Db::table("pay_order_kl_config")->where($where)->page($page, $limit)->order($order)->select();

        $channel_id_gh = array_unique(array_column($list, 'channel_id'));
        $channels = Db::table('cms_manager_user')->where('id', 'in', $channel_id_gh)->column('id,account');

        $agent_id_gh = array_unique(array_column($list, 'agent_id'));
        $agents = Db::table('cms_manager_user')->where('id', 'in', $agent_id_gh)->column('id,account');

        foreach ($list as $k => $v) {
            $list[$k]['dateMoney'] = $v['money'];
            if ($start_date || $end_date) {
                /**
                 * 日期范围金额
                 */
                $itemWhere = [];
                $itemWhere[] = ['channel_id', '=', $v['channel_id']];
                $itemWhere[] = ['status', '=', 2];
                if ($start_date && $end_date) {
                    $itemWhere[] = ['create_date', '>=', $start_date];
                    $itemWhere[] = ['create_date', '<=', $end_date];
                } elseif ($start_date) {
                    $itemWhere[] = ['create_date', '>=', $start_date];
                } elseif ($end_date) {
                    $itemWhere[] = ['create_date', '<=', $end_date];
                }
                $list[$k]['dateMoney'] = Db::table("pay_order_kl_backups")->where($itemWhere)->sum('total_fee') ?? 0;
            }
            $list[$k]['dateMoney'] = getQuotient($list[$k]['dateMoney'], 100);
            $list[$k]['money'] = getQuotient($v['money'], 100);

            $list[$k]['channel_name'] = isset($channels[$v['channel_id']]) ? $channels[$v['channel_id']] : '';
            $list[$k]['agent_name'] = isset($agents[$v['agent_id']]) ? $agents[$v['agent_id']] : '';

        }
        $count = Db::table("pay_order_kl_config")->where($where)->count();
        return tableJson($list, $count);
    }

    /**
     * 订单列表
     * @return mixed|\think\response\Json
     */
    public function orderList(){
        if (request()->isAjax()) {
            $status = input('status');
            $channel_id = input('channel_id');
            $agent_id = input('agent_id');
            $start_date = input('start_date');
            $end_date = input('end_date');
            $user_reg_date = input('user_reg_date');
            $uid = input('uid');
            $out_trade_no = input('out_trade_no');
            $trade_no = input('trade_no');
            $chargefrom = input('chargefrom');
            $page = input('page', 1);
            $limit = input('limit', 10);
            $where = [];
            if ($status != '') {
                $where[] = ['status', '=', $status];
            }
            if ($channel_id != '') {
                $where[] = ['channel_id', '=', $channel_id];
            }
            if ($agent_id != '') {
                $where[] = ['agent_id', '=', $agent_id];
            }
            if ($start_date != '') {
                $where[] = ['create_date', '>=', $start_date];
            }
            if ($end_date != '') {
                $where[] = ['create_date', '<=', $end_date];
            }
            if ($user_reg_date != '') {
                $where[] = ['user_reg_date', '=', $user_reg_date];
            }
            if ($uid != '') {
                $where[] = ['uid', '=', $uid];
            }
            if ($out_trade_no != '') {
                $where[] = ['out_trade_no', '=', $out_trade_no];
            }
            if ($trade_no != '') {
                $where[] = ['trade_no', '=', $trade_no];
            }
            if ($chargefrom != '') {
                $where[] = ['chargefrom', '=', $chargefrom];
            }
            $list = KlOrder::with(['agent','channel'])->where($where)->page($page, $limit)->order("id desc")->select();
            foreach ($list as $k => $v){
                $list[$k]['money'] = getQuotient($v['total_fee'], 100);
            }
            $count = KlOrder::where($where)->count();
            $totalRow['total_fee'] = KlOrder::with(['agent', 'channel'])->where($where)->sum('total_fee');
            $totalRow['total_fee'] = getQuotient($totalRow['total_fee'], 100);
            return json(['code' => 0, 'msg' => 'ok', 'count' => $count, 'data' => $list, 'totalRow' => $totalRow]);
        }
        return $this->fetch();
    }
}